<?php


namespace App\Http\Controllers\Common;


use App\Http\Controllers\Controller;
use App\Models\VerificationCode;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Overtrue\EasySms\EasySms;

class VerifyCodeController extends Controller
{
    /**
     * 发送短信验证码
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\BobException
     * @throws \Overtrue\EasySms\Exceptions\InvalidArgumentException
     */
    public function postSendCode(Request $request)
    {
        $map = [
            'mail' => 'email',
            'sms' => 'phone',
        ];
        $user = $request->user()->id ?? null;

        foreach ($map as $channel => $input) {

            if (!($account = $request->input($input))) {
                continue;
            }

            $this->send($account, $channel, [
                'user_id' => $user,
            ]);
            break;
        }

        return $this->sendSuccess('短信发送成功');
    }

    /**
     * 发送验证
     *
     * @param string $account
     * @param string $channel
     * @param array $data
     * @throws \App\Exceptions\BobException
     * @throws \Overtrue\EasySms\Exceptions\InvalidArgumentException
     */
    public function send(string $account, string $channel = '', array $data = [])
    {
        $this->validateSent($account, $channel);

        $data['account'] = $account;
        $data['channel'] = $channel;
        $model = factory(\App\Models\VerificationCode::class)->create($data);
        $config = config('sms');
        try {
            $easySms = new EasySms($config);
            $easySms->send($account, [
                'content' => sprintf('【优米出行】您的验证码是%s。如非本人操作，请忽略本短信', $model->code),
                'template' => '3327328',
                'data' => [
                    'code' => $model->code
                ],
            ]);
        } catch (\Overtrue\EasySms\Exceptions\NoGatewayAvailableException $exception) {
            $model->forceDelete();
            return_bob($exception->getExceptions()['yunpian']->getMessage());
        }
    }

    /**
     * Validate sent.
     *
     * @param string $account
     * @param string $channel
     * @return void
     * @throws \App\Exceptions\BobException
     * @author Bob<bob@bobcoder.cc>
     */
    protected function validateSent(string $account, string $channel)
    {
        //$vaildSecond = config('app.env') == 'production' ? 60 : 6;
        $vaildSecond = 60;
        $verify = VerificationCode::where('account', $account)
            ->byValid($vaildSecond)
            ->orderBy('id', 'desc')
            ->first();

        if ($verify) {
            return_bob(sprintf('还需要%d秒后才能获取', $verify->makeSurplusSecond($vaildSecond)));
        }

        $result = $this->astrict($channel);
        if (is_string($result)) return_bob($result);
    }


    /**
     * 验证短信验证码条数
     * @param $type
     * @return bool|string
     */
    protected function astrict($type)
    {
        if ($type != 'sms') {
            return true;
        }

        // 验证一天
        $verify = VerificationCode::query()
            ->whereBetween('created_at', $this->getPrcTimeScope())
            ->count();
        if ($verify >= 10) {
            return '请勿频繁获取';
        }

        // 验证一小时
        $verify = VerificationCode::query()
            ->byValid(3600)
            ->count();
        if ($verify >= 5) {
            return '请勿频繁获取';
        }

        return true;
    }

    /**
     * 获取每日时间区间.
     * @return array
     * @author: Bob
     */
    public function getPrcTimeScope()
    {
        $date = Carbon::now()->toDateString();
        $start = (date('Y-m-d', strtotime($date . ' 00:00:00'))) . " 00:00:00";
        $end = $date . ' 23:59:59';

        return [$start, $end];
    }
}
